package com.smarthospital.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smarthospital.common.Result.CodeMsg;
import com.smarthospital.common.Result.CommonException;
import com.smarthospital.common.Result.ResultDTO;
import com.smarthospital.contants.SHConst;
import com.smarthospital.entity.dto.*;
import com.smarthospital.entity.pojo.User;
import com.smarthospital.entity.vo.RefundsVO;
import com.smarthospital.service.PayService;
import com.smarthospital.service.impl.PayServiceImpl;
import com.smarthospital.web.inteceptor.LoginInterceptor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.util.concurrent.TimeUnit;

/**
 * create by sym  2020/8/16 16:00.
 */
@RestController
@Slf4j
@RequestMapping("/pay")
@Api(description = "支付接口",value = "pay")
public class PayController {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PayService payService = new PayServiceImpl();

    @GetMapping("/prePayOder")
    @ApiOperation(value = "去支付",
            notes =" 立即付款页面\n " +
                    "param: docterId -> 医生id\n" +
                    "       payType -> 支付类型 0_微信(默认可以不传,目前支支持微信) \n" +
                    "       inquiryTime -> 问诊时间段  2021-05-28 08:30 \n" +
                    "       inquiryType -> 问诊类型  0_图文问诊 1_电话问诊 2_视频问诊" )
    public ResultDTO prePayOder(@RequestParam("docterId")Integer docterId,@RequestHeader("SH_TOKEN")String SH_TOKEN,
                                @RequestParam(value = "payType",required = false)Integer payType,
                                @RequestParam(value = "inquiryTime")String inquiryTime,
                                @RequestParam(value = "inquiryType")Integer inquiryType) throws URISyntaxException, IOException, InvalidKeyException {
        User user = LoginInterceptor.getUser();
        String key = String.format(SHConst.redis_key.prePayOder,user.getId()) ;
        if (!redisTemplate.opsForValue().setIfAbsent(key,"1",1,TimeUnit.SECONDS)) {
            throw new CommonException(CodeMsg.ERROR_OP_FAST);
        }
        PrePayResultDTO object =  payService.prePayOder(docterId,payType,inquiryType,inquiryTime);
        return ResultDTO.sucess(object);
    }

    @PostMapping("/payCallBack")
    @ApiOperation(value = "支付回调",
            notes =" 提供给微信服务器的支付回调\n " +
                    "解析请求头，获取订单信息，修改订单状态\n" )
    public WxPayCallBackResultDTO payCallBack(HttpServletRequest request, @RequestBody JSONObject parm) throws URISyntaxException, IOException, InvalidKeyException {
        log.info("【微信支付回调】 param {}",parm);
        try {
            payService.payCallBack(request,parm);
            return WxPayCallBackResultDTO.sucess();
        } catch (Exception e) {
            log.error("【微信支付回调】 err {}",e.getMessage(),e);
            return WxPayCallBackResultDTO.fail();
        }

    }

    @GetMapping("/closeOrder")
    @ApiOperation(value = "关闭订单",
            notes =" 用户点击取消待支付订单时即可关闭订单\n " +
                    "codeMsg： 10510,\"订单已经支付\"\n" )
    public ResultDTO closeOrder(@RequestHeader("SH_TOKEN")String SH_TOKEN, @RequestParam("orderId")String orderId) throws Exception {
        log.info("【关闭订单】 orderId {}",orderId);
        payService.closeOrder(orderId);
        return ResultDTO.sucess();

    }

    @GetMapping("/queryOrder")
    @ApiOperation(value = "查询订单",
            notes =" 查询订单支付状态订单,支付完成5秒调用\n " )
    public ResultDTO queryOrder(@RequestHeader("SH_TOKEN")String SH_TOKEN, @RequestParam("orderId")String orderId) throws Exception {
        log.info("【查询订单】 orderId {}",orderId);
        WXQueryOderDTO wxQueryOderDTO = payService.queryOrder(orderId);
        return ResultDTO.sucess(wxQueryOderDTO);

    }

    @GetMapping("/refunds")
    @ApiOperation(value = "退款接口",
            notes =" 用户发起退款申请\n " +
                    "param reason -> 退款原因\n" +
                    "      out_trade_no -> 订单号" )
    public ResultDTO refunds(@RequestHeader("SH_TOKEN")String SH_TOKEN, @RequestParam("out_trade_no") String out_trade_no
            , @RequestParam("reason") String reason) throws Exception {
        //后面会把用户信息打在日志里 所以不用加用户信息
        log.info("【退款接口】 out_trade_no {} reason {}", out_trade_no,reason);
        RefundsDTO refundsDTO = payService.refunds(out_trade_no,reason);
        return ResultDTO.sucess(refundsDTO);

    }




}
